package ca.cbc.msb.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ReadAndWriteFileUtil 
{
	private static Logger logger = LoggerFactory.getLogger(ReadAndWriteFileUtil.class);
	private String filePathStr;

	public ReadAndWriteFileUtil(String filePathStr)
	{
		//make directories if not exist
		if(filePathStr.contains("/") || filePathStr.contains("\\"))
		{
			String dirStr = "\\";
			if(filePathStr.contains("/"))
				dirStr = "/";
			
			String[] tmpStrArray = filePathStr.split(dirStr);
			for(int i=0; i<tmpStrArray.length-1; i++)
			{
				String fileNameStr = tmpStrArray[0];
				for(int j=1; j<=i; j++)
					fileNameStr += dirStr + tmpStrArray[j];					
					
				File file = new File(fileNameStr);
				if(file.exists() == false)
					file.mkdirs();
			}
		}
		this.setFilePathStr(filePathStr);
	}
	
	public String readLine()
	{
		FileReader fr = null;
		BufferedReader br = null;
		String lastLineStr = null;
		try {
			fr = new FileReader(filePathStr);
		    br = new BufferedReader(fr);
		    lastLineStr = br.readLine();
		    if(lastLineStr == null)
		    	logger.warn(filePathStr + " is empty!");
		    
		    if(br.readLine() != null)
		    	logger.error("There are more than one line in " + filePathStr);
		    
			//logger.debug("Read {} from {}...", lastLineStr, filePathStr);
		} catch (IOException e) {
			logger.info("IOException when reading file, not found it most likly...");
		} finally {
		    if (fr != null)
				try {
					fr.close();
				} catch (IOException e) {
					logger.error("Error trying to close file...", e);
				}
			if (br !=null)
				try {
					br.close();
				} catch (IOException e) {
					logger.error("Error trying to close file...", e);
				}
		}
		
		return lastLineStr;
	}
	
	public void writeLine(String messageStr)
	{
		FileOutputStream fos = null;	
		PrintWriter pw = null;
		try {
			fos = new FileOutputStream(new File(filePathStr), false);
			pw = new PrintWriter(fos);
			pw.println(messageStr);
			pw.flush();
			
			//logger.debug("Writen {} to {}...", messageStr, filePathStr);
		} catch (FileNotFoundException e) {
			logger.error("File not found exception..", e);
		}
		finally{
			if(fos != null)
				try {
					fos.close();
				} catch (IOException e) {
					logger.error("Error trying to close file...", e);
				}
			if(pw != null)
				pw.close();
		}	
	}
	
	public String getFilePathStr() {
		return filePathStr;
	}

	public void setFilePathStr(String filePathStr) {
		this.filePathStr = filePathStr;
	}

}
